﻿using KPIS.GERP.Models;
using KPIS.GERP.Models.ICM;
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using System.Data.Entity;
using KeepAutomation.Barcode.Bean;
using KeepAutomation.Barcode;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class ParcelControlAssetListController : Controller
    {
        public ActionResult Index()
        {
            var service = new AssetService.AssetServiceClient();

            return View(service.SelectAsset(new Models.ICM.Asset { RecordStatus = "!D" }, new[] { "MasUnit" }));
        }

        #region Asset

        public ActionResult IndexAsset()
        {
            return View();
        }

        public ActionResult AssetDetails(int AssetId, string statusMessage = "")
        {
            var service = new AssetService.AssetServiceClient();

            ViewBag.AssetId = AssetId;
            ViewBag.statusMessage = statusMessage;

            var model = service.SelectAssetDetail(new Models.ICM.Asset { AssetId = AssetId, IsLowerAsset = false }, new[] { 
                "MasUnit", "MasResourceType", "AssetStatus", "MasResourceSubGroup", 
                "MasDepreciationType", "Warehouse", "ProjectExpense.Project", "MasResourceGroup"
                , "ProjectExpense.MasBudgetSource", "ProjectExpense.MasBudgetExpense.MasBudgetExpenseGroup"
                , "ReceiveDtl.Received.ReceiveType"}).FirstOrDefault();

            if (model == null)
            {
                model = service.SelectAssetDetail(new Models.ICM.Asset { AssetId = AssetId, IsLowerAsset = true }, new[] { 
                "MasUnit", "MasResourceType", "AssetStatus", "MasResourceSubGroup", 
                "MasDepreciationType", "Warehouse", "ProjectExpense.Project", "MasResourceGroup"
                , "ProjectExpense.MasBudgetSource", "ProjectExpense.MasBudgetExpense.MasBudgetExpenseGroup"
                , "ReceiveDtl.Received.ReceiveType"}).FirstOrDefault();
            }

            return View(model);
        }

        public ActionResult GetResItemProperty(int resitemid)
        {
            var db = new GERPContext(true);
            var resItem = db.MasResourceItems
                .Include(o=>o.MasResourceSubGroup.MasResourceGroup.MasDepreciationType)
                .First(o=>o.ResItemId == resitemid);
            return Json(new
            {
                ResItemId = resItem.ResItemId,
                ResSubGrpId = resItem.ResSubGrpId,
                ResSubGrpText = resItem.MasResourceSubGroup != null ? resItem.MasResourceSubGroup.Name : "",
                ResGrpId = resItem.MasResourceSubGroup != null ? resItem.MasResourceSubGroup.ResGrpId : 0,
                ResGrpText = resItem.MasResourceSubGroup != null && resItem.MasResourceSubGroup.MasResourceGroup != null ?
                resItem.MasResourceSubGroup.MasResourceGroup.Name : "",
                ResTypeId = resItem.MasResourceSubGroup != null && resItem.MasResourceSubGroup.MasResourceGroup != null ?
                resItem.MasResourceSubGroup.MasResourceGroup.ResTypeId : 0,
                UnitId = resItem.UnitId,
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetDepreciationTypeProperty(int DpTypeId)
        {
            var db = new GERPContext(true);
            var resItem = db.MasDepreciationTypes
                .First(o => o.DpTypeId == DpTypeId);
            return Json(new
            {
                resItem.DpTypeId,
                resItem.Name,
                resItem.DpRateYear
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetResItems(FormCollection formCollection)
        {
            var db = new GERPContext(true);
            var resItems = db.MasResourceItems
                .Include(o => o.MasResourceSubGroup.MasResourceGroup.MasResourceType)
                .Where(o => o.RecordStatus != "D")
                .OrderBy(o => o.Code);
            var datas = resItems.Select(resItem => new
            {
                ResItemId = resItem.ResItemId,

                ResItemName = "[" + resItem.Code + "] " + 
                resItem.Name + " - " +

                              (resItem.MasResourceSubGroup != null &&
                               resItem.MasResourceSubGroup.MasResourceGroup != null &&
                               resItem.MasResourceSubGroup.MasResourceGroup.MasResourceType != null
                                  ? resItem.MasResourceSubGroup.MasResourceGroup.MasResourceType.Name
                                  : "..") + "/" +

                              (resItem.MasResourceSubGroup != null &&
                               resItem.MasResourceSubGroup.MasResourceGroup != null
                                  ? resItem.MasResourceSubGroup.MasResourceGroup.Name
                                  : "..") + "/" +

                              (resItem.MasResourceSubGroup != null ? resItem.MasResourceSubGroup.Name : ""),

                ResSubGrpId = resItem.ResSubGrpId,

                ResSubGrpText = resItem.MasResourceSubGroup != null ? resItem.MasResourceSubGroup.Name : "",

                ResGrpId = resItem.MasResourceSubGroup != null ? resItem.MasResourceSubGroup.ResGrpId : 0,

                ResGrpText =
                    resItem.MasResourceSubGroup != null && resItem.MasResourceSubGroup.MasResourceGroup != null
                        ? resItem.MasResourceSubGroup.MasResourceGroup.Name
                        : "",

                ResTypeId =
                    resItem.MasResourceSubGroup != null && resItem.MasResourceSubGroup.MasResourceGroup != null
                        ? resItem.MasResourceSubGroup.MasResourceGroup.ResTypeId
                        : 0,

                UnitId = resItem.UnitId,
            });
            return Json(datas, JsonRequestBehavior.AllowGet);
        }

        [HttpPost,ValidateAntiForgeryToken]
        public ActionResult UploadPictureAsset(Asset model, HttpPostedFileBase file, int assetId)
        {
            var service = new AssetService.AssetServiceClient();

            try
            {
                string fileName = model.PicturePath;
                string Description = model.Description;
                string Remark = model.Remark;
                string SerialNumber = model.SerialNumber;
                int stratus = model.AssetStatusId;

                if (ModelState.IsValidField(model.AssetId.ToString()))
                {
                    ViewData["file_error"] = "";

                    if (file != null && file.ContentLength > 0)
                    {
                        string file_ext = Path.GetExtension(file.FileName);
                        if (!FileType(file_ext))
                        {
                            ViewData["file_error"] = "การอัพโหลดรูปต้องเป็นประเภท JPEG,PNG หรือ GIF เท่านั้น!";
                            return View(model);
                        }

                        string FolderName = model.AssetId.ToString();
                        string folder_path = Server.MapPath("~/Content/Ace/assets/Asset");// + "/" + FolderName);

                        DirectoryInfo di = new DirectoryInfo(folder_path);
                        if (!di.Exists)
                        {
                            System.IO.Directory.CreateDirectory(folder_path);
                            FolderACL("Everyone", folder_path);
                        }

                        fileName = DateTime.Now.Ticks.ToString() + Path.GetFileName(file.FileName);

                        model.PicturePath = Path.Combine(fileName);
                        var path = (folder_path + "/" + fileName);
                        file.SaveAs(path);
                        fileName = model.PicturePath;
                    }

                    ViewBag.assetId = assetId;

                    var selectsupplies = new AssetService.AssetServiceClient();
                    var modelAssetToDb = selectsupplies.SelectAsset(new Asset { AssetId = assetId, IsLowerAsset = false }, null).FirstOrDefault();

                    if (modelAssetToDb == null)
                    {
                        modelAssetToDb = selectsupplies.SelectAsset(new Asset { AssetId = assetId, IsLowerAsset = true }, null).FirstOrDefault();
                    }

                    modelAssetToDb.ResItemId = model.ResItemId;
                    modelAssetToDb.ResGrpId = model.ResGrpId;
                    modelAssetToDb.ResSubGrpId = model.ResSubGrpId;
                    modelAssetToDb.UnitId = model.UnitId;
                    modelAssetToDb.PicturePath = fileName;
                    modelAssetToDb.Description = Description;
                    modelAssetToDb.Remark = Remark;
                    modelAssetToDb.SerialNumber = SerialNumber;
                    modelAssetToDb.AssetStatusId = stratus;
                    modelAssetToDb.AssetCode = model.AssetCode;
                    modelAssetToDb.AssetName = model.AssetName;
                    modelAssetToDb.IsLowerAsset = model.IsLowerAsset;
                    modelAssetToDb.Place = model.Place;
                    // modelAssetToDb.Quantity = model.Quantity;
                    modelAssetToDb.Price = model.Price;
                    modelAssetToDb.WhId = model.WhId;
                    modelAssetToDb.Description = model.Description;
                    modelAssetToDb.AssetDate = model.AssetDate; 
                    modelAssetToDb.QualityAssuranceExpireDate = model.QualityAssuranceExpireDate;
                    modelAssetToDb.DepreciationTypeId = model.DepreciationTypeId;
                    
                    var id = service.InsertPictureAsset(modelAssetToDb, Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("AssetDetails", new { AssetId = assetId, statusMessage = "1" });
                }
            }
            catch (Exception ex)
            {
                ViewData["file_error"] = "ไม่สามารถเพิ่มรูปภาพแนบได้:" + ex.Message;
                return View(model);
            }
            return View("AssetDetails", new { assetId = model.AssetId, statusMessage = "1" });
        }
         
        public ActionResult DeleteAsset(int id)
        {
            var db = new GERPContext(true);
            db.Database.ExecuteSqlCommand("update icmasset set recordstatus='D' where assetid=" + id + ";");
            return RedirectToAction("AssetDetails", new { AssetId = id, statusMessage = "2" }); 
        }

        public void GenderateBarcode(int AssetId, string AssetCode, string AssetName)
        {
            string strFileFullName = Server.MapPath("~/Temp/" + AssetCode);

            Bitmap bitmap = new Bitmap(AssetCode.Length * 15, 100);
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                Font font = new Font("Code39AzaleaRegular2", 25);
                //PointF point = new PointF(0, 2f);
                SolidBrush black = new SolidBrush(Color.Black);
                SolidBrush white = new SolidBrush(Color.White);
                var sf = new StringFormat()
                {
                    Alignment = StringAlignment.Center,
                    //LineAlignment = StringAlignment.Center,
                };
                graphics.FillRectangle(white, 0, 0, bitmap.Width, bitmap.Height);
                graphics.DrawString("*" + AssetCode + "*", font, black, new Rectangle(0, 5, bitmap.Width, bitmap.Height), sf);
                sf = new StringFormat()
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center,
                };
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                graphics.DrawString(AssetCode, new Font("Tahoma", 8), black, new Rectangle(0, -5, bitmap.Width, bitmap.Height), sf);
                graphics.DrawString(AssetName, new Font("Tahoma", 10), black, new Rectangle(0, 30, bitmap.Width, bitmap.Height), sf);
            }

            bitmap.Save(strFileFullName, ImageFormat.Png);

            //BarCode barcode = new BarCode();
            //barcode.Symbology = KeepAutomation.Barcode.Symbology.EAN13;
            //barcode.CodeToEncode = AssetCode;
            //barcode.BarcodeUnit = BarcodeUnit.Pixel;
            //barcode.ImageFormat = ImageFormat.Png;
            //barcode.TopMargin = 10;
            //barcode.LeftMargin = 10;
            //barcode.RightMargin = 10;

            //barcode.generateBarcodeToImageFile(strFileFullName);

            //BarCodeBuilder builder = new BarCodeBuilder(AssetCode, Symbology.EAN13);
            //Caption caption = new Caption();
            //caption.Text = AssetName;
            //caption.TextAlign = System.Drawing.StringAlignment.Center;
            //caption.Visible = true;
            //caption.ForeColor = System.Drawing.Color.Black;
            //builder.CaptionBelow = caption;

            //

            //builder.Save(strFileFullName, BarCodeImageFormat.Png);
            Response.Clear();
            Response.ContentType = "text/plain";
            Response.WriteFile(strFileFullName);
            Response.AddHeader("Content-Disposition", "attachment;filename=" + AssetCode + ".png");
            Response.End();
        }
        #endregion

        #region OfficeSuppliesLot

        public ActionResult IndexOfficeSuppliesLot()
        {
            var service = new OfficeSuppliesLotService.OfficeSuppliesLotServiceClient();
            var officeSuppliesLots = service.SelectSuppliesLot(new Models.ICM.OfficeSuppliesLot { RecordStatus = "!D" },
                new[] {"MasResourceItem", "MasUnit", "ProjectExpense.Project", "ReceiveDtl", "Warehouse"});

            return View(officeSuppliesLots);
        }

        public ActionResult OfficeSuppliesLotDetails(int officeSuppliesLotId)
        {
            var service = new OfficeSuppliesLotService.OfficeSuppliesLotServiceClient();

            ViewBag.officeSuppliesLotId = officeSuppliesLotId;

            var model = service.SelectSuppliesLotDetail(new Models.ICM.OfficeSuppliesLot { RecordStatus = "!D", OfficeSuppliesLotId = officeSuppliesLotId }, new[] { "MasResourceItem", "MasUnit", "ProjectExpense", "ReceiveDtl", "Warehouse"
                                                                                                                                                                      , "ProjectExpense.Project", "ProjectExpense.MasBudgetSource"}).FirstOrDefault();

            return View(model);
        }

        public ActionResult PopupOfficeSuppliesLot(int officeSuppliesLotId)
        {
            var service = new OfficeSuppliesLotService.OfficeSuppliesLotServiceClient();

            ViewBag.officeSuppliesLotId = officeSuppliesLotId;

            var model = service.SelectSuppliesLot(new Models.ICM.OfficeSuppliesLot { RecordStatus = "!D", OfficeSuppliesLotId = officeSuppliesLotId }, new[] { "MasResourceItem", "MasUnit", "ProjectExpense", "Project", "ReceiveDtl", "Warehouse" }).FirstOrDefault();

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UploadPictureOfficeSuppliesLot(KPIS.GERP.Models.ICM.OfficeSuppliesLot model, HttpPostedFileBase file, int officeSuppliesLotId)
        {
            try
            {
                string fileName = model.PicturePath;
                string remark = model.Remark;
                string Description = model.Description;

                if (ModelState.IsValidField(model.OfficeSuppliesLotId.ToString()))
                {
                    ViewData["file_error"] = "";

                    if (file != null && file.ContentLength > 0)
                    {
                        string file_ext = Path.GetExtension(file.FileName);
                        if (!FileType(file_ext))
                        {
                            ViewData["file_error"] = "การอัพโหลดรูปต้องเป็นประเภท JPEG,PNG หรือ GIF เท่านั้น!";
                            return View(model);
                        }

                        //string FolderName = model.OfficeSuppliesLotId.ToString();
                        string folder_path = Server.MapPath("~/Content/Ace/assets/OfficeSuppiles");//+ "\\" + FolderName);

                        DirectoryInfo di = new DirectoryInfo(folder_path);
                        if (!di.Exists)
                        {
                            System.IO.Directory.CreateDirectory(folder_path);
                            FolderACL("Everyone", folder_path);
                        }

                        fileName = DateTime.Now.Ticks.ToString() + Path.GetFileName(file.FileName);
                        var path = (folder_path +"/"+fileName);
                        model.PicturePath = Path.Combine(fileName);
                        file.SaveAs(path);
                        fileName = model.PicturePath;
                     }
                     
                    ViewBag.officeSuppliesLotId = officeSuppliesLotId;

                    var selectsupplies = new OfficeSuppliesLotService.OfficeSuppliesLotServiceClient();
                    List<OfficeSuppliesLot> List = selectsupplies.SelectSuppliesLot(new OfficeSuppliesLot { OfficeSuppliesLotId = officeSuppliesLotId }, null).ToList();
                    foreach (OfficeSuppliesLot item in List)
                    {
                        item.PicturePath = fileName;
                        item.Remark = remark;
                        item.Description = Description;
                    }

                    var service = new OfficeSuppliesLotService.OfficeSuppliesLotServiceClient();
                    var id = service.InsertPicture(List.FirstOrDefault(),Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("IndexOfficeSuppliesLot");
                }
            }
            catch (Exception ex)
            {
                ViewData["file_error"] = "ไม่สามารถเพิ่มรูปภาพแนบได้:" + ex.Message;
                return View(model);
            }
            return View(officeSuppliesLotId = model.OfficeSuppliesLotId);
        }

        public static void FolderACL(String accountName, String folderPath)
        {
            FileSystemRights Rights;

            //What rights are we setting?
            Rights = FileSystemRights.FullControl;
            bool modified;
            InheritanceFlags none = new InheritanceFlags();
            none = InheritanceFlags.None;

            //set on dir itself
            FileSystemAccessRule accessRule = new FileSystemAccessRule(accountName, Rights, none, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
            DirectoryInfo dInfo = new DirectoryInfo(folderPath);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            dSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);

            //Always allow objects to inherit on a directory 
            InheritanceFlags iFlags = new InheritanceFlags();
            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            //Add Access rule for the inheritance
            FileSystemAccessRule accessRule2 = new FileSystemAccessRule(accountName, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
            dSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified);

            dInfo.SetAccessControl(dSecurity);
        }

        public bool FileType(String file_extentions)
        {
            bool ret = false;

            if (file_extentions.ToLower().StartsWith(".jpg"))
                ret = true;
            else if (file_extentions.ToLower().StartsWith(".png"))
                ret = true;
            else if (file_extentions.ToLower().StartsWith(".gif"))
                ret = true;
            else
                ret = false;

            return ret;

        }

        #endregion

    }
}